import {baseURL} from './base.js'

// 刷新Token的方法
function refreshToken() {
    return new Promise((resolve, reject) => {
        // 这里调用实际的刷新Token接口
        uni.request({
            url: baseURL + '/app-api/member/auth/refresh-token?refreshToken='+ uni.getStorageSync('refreshToken'),
            method: 'POST',
			header: {
				"tenant-id": "1"
			},
			data: {
                'refreshToken': uni.getStorageSync('refreshToken')
            },
            success: (res) => {
                if (res.data.code === 0) {
                 
					uni.setStorageSync("token", res.data.data.accessToken)
					// uni.setStorageSync("openid", res.data.data.openid)
					uni.setStorageSync("refreshToken", res.data.data.refreshToken)
					uni.setStorageSync("userId", res.data.data.userId)
                    resolve(res.data.data.accessToken);
                } else {
                    reject(new Error('Refresh token failed'));
                }
            },
            fail: reject
        });
    });
}

let isRefreshing = false;
let failedQueue = [];

const myRequest = function(options) {
    return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token');
        var merged = options.data;
        // let header = {
        //     "tenant-id": "1"
        // };

        // if (options.header !== "noAuth") {
        //     header['Authorization'] = "Bearer " + token;
        // }
		if (merged && merged.hasOwnProperty("userId")) {
           merged.userId =  uni.getStorageSync('userId');
        }
        const send = () => {
            uni.request({
                url: baseURL + options.url,
                data: merged,
                header:{
					 "tenant-id": "1",
					 "Authorization": "Bearer " +uni.getStorageSync('token')
				},
                method: options.method,
                success: (res) => {
                    switch (res.data.code) {
                        case 0:
                        case 200:
                            resolve(res.data);
                            break;
                        case 410000:
                        case 410001:
                        case 410002:
                        case 401:
                            if (!isRefreshing) {
                                isRefreshing = true;
                                refreshToken().then(newToken => {
                                    uni.setStorageSync('token', newToken);
                                    isRefreshing = false;
                                    // 重新发送之前失败的请求
                                    failedQueue.forEach(cb => cb());
                                    failedQueue = [];
                                }).catch(() => {
                                    isRefreshing = false;
                                    uni.reLaunch({
                                        url: '/pages/login/login'
                                    });
                                });
                            }
                            failedQueue.push(() => send());
                            break;
                        default:
                            reject(res.data);
                            if (!options.hidetoast) {
                                uni.showToast({
                                    title: res.data.msg || res.data.message || '系统未知错误',
                                    duration: 2000,
                                    icon: 'none'
                                });
                            }
                            break;
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '请求失败',
                        duration: 2000,
                        icon: 'none'
                    });
                    reject(err);
                }
            });
        };

        send();
    });
};

module.exports = {
    myRequest
};